<template>
  <div class="materal">
    <div class="materal-left">
      <c-table
        row-key="id"
        class="table-template__table"
        :isResetButton="false"
        :data="tableData"
        :loading="tableLoading"
      >
        <!-- 操作栏 -->
        <!-- 搜索栏 -->
        <template #search>
          <c-select
            width="200px"
            v-model="searchParams.temp_number_id"
            prefixText="序号样式："
            :optionList="TempNumber"
            @change="onRefreshMateral"
          ></c-select>
          <c-select
            width="200px"
            v-model="searchParams.mini_ent_type"
            prefixText="小程序入口："
            :clearable="false"
            @change="onRefreshMateral"
          >
            <el-option
              v-for="item in MiniEnt"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >
              <span class="mini-ent-select">
                <span>{{ item.label }}</span>
                <span v-if="item.desc">描述：{{ item.desc }}</span>
              </span>
            </el-option>
          </c-select>
        </template>
        <template #table>
          <el-table-column label="排序" width="60" align="center">
            <template #default>
              <img class="table-drag-img" src="@/assets/common/drag.svg" />
            </template>
          </el-table-column>
          <el-table-column prop="id" label="图片" min-width="210">
            <template #default="{ row, $index }">
              <el-space :size="10" style="width: 100%" wrap>
                <c-select
                  width="140px"
                  v-model="row.image_type"
                  prefixText="类型："
                  :loading="tempLoading"
                  :optionList="tempData.data"
                  @change="onImageTypeChange(row)"
                ></c-select>
                <c-select
                  width="140px"
                  :disabled="!row.image_type"
                  v-model="row.image_temp_id"
                  prefixText="样式："
                  :optionList="getTempMap?.[row.image_type]?.tempList || []"
                  @change="onRefreshMateral"
                ></c-select>
                <el-button
                  @click="handleImageModal(row, $index)"
                  :disabled="!row.image_type || !row.image_temp_id"
                >
                  选择
                </el-button>
              </el-space>
              <div class="select-box" v-if="row.image_list.length || row.text_list.length">
                <template v-if="row.image_type == 5">
                  <div class="scroller-image" v-for="item in row.image_list" :key="item._id">
                    <img
                      v-for="item in item.images"
                      :key="item"
                      class="scroller-image-item"
                      :src="item.url"
                    />
                  </div>
                </template>
                <template v-else>
                  <el-space class="image-list" :size="4" wrap>
                    <img
                      class="image-list-item"
                      v-for="item in row.image_list"
                      :key="item._id"
                      :src="item.images[0].url"
                    />
                  </el-space>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="文案" min-width="160">
            <template #default="{ row, $index }">
              <el-space :size="10" style="width: 100%" wrap>
                <c-select
                  width="140px"
                  v-model="row.text_temp_id"
                  prefixText="样式："
                  :optionList="getTempMap?.[row.image_type]?.textList || []"
                  :disabled="!row.image_type"
                  @change="onRefreshMateral"
                ></c-select>
                <el-button
                  @click="handleTextModal(row, $index)"
                  :disabled="!row.image_type || !row.text_temp_id"
                >
                  选择
                </el-button>
              </el-space>
              <div class="select-box" v-if="row.image_list.length || row.text_list.length">
                <div class="text-item" v-for="item in row.text_list" :key="item._id">
                  {{ item.content }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="{ row, $index }">
              <el-button type="danger" text @click="handleDelete(row, $index)">删除</el-button>
            </template>
          </el-table-column>
        </template>
        <template #table-footer>
          <div style="margin-top: 10px" class="is-error-text" v-if="!isCan">
            还有未选择的内容！！
          </div>
          <div class="materal-table-footer">
            <el-button text type="primary" @click="handleAddMateral"> + 添加</el-button>
          </div>
        </template>
      </c-table>
      <div class="materal-footer">
        <el-button plain @click="handleCancel"> 取 消 </el-button>
        <el-button type="primary" plain @click="initGenerateMateral" :disabled="!isCan">
          预 览
        </el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!isCan"> 创建素材 </el-button>
      </div>
    </div>
    <div
      class="materal-right"
      v-loading="previewLoading"
      v-if="globalStore.device.type == 'desktop'"
    >
      <div class="materal-right-title is-title">预览</div>
      <div class="materal-right-preview">
        <material-preview ref="materialRef"></material-preview>
      </div>
    </div>
  </div>

  <c-dialog
    title="选择图片"
    :width="globalStore.device.type == 'desktop' ? '1200' : '90%'"
    name="select-image-popup"
  >
    <select-image-popup
      :userType="userType"
      :rowCount="getRowCount"
      :itemSize="getItemSize"
      :imageType="getImageType"
      @on-end="onSelectImageEnd"
    ></select-image-popup>
  </c-dialog>

  <c-dialog
    title="选择文案"
    :width="globalStore.device.type == 'desktop' ? '1200' : '90%'"
    name="select-text-popup"
  >
    <select-text-popup :userType="userType" @on-end="onSelectTextEnd"></select-text-popup>
  </c-dialog>

  <c-dialog title="预览素材" :width="600" name="material-preview-popup">
    <material-preview-popup></material-preview-popup>
  </c-dialog>

  <c-dialog
    title="复制素材"
    :close-on-click-modal="true"
    :width="globalStore.device.type == 'desktop' ? '1200' : '90%'"
    name="material-copy-popup"
  >
    <material-preview-popup isCopy isCover :isPreview="false"></material-preview-popup>
  </c-dialog>

  <c-dialog title="确定创建素材？" :width="600" name="material-confirm-popup">
    <material-confirm-popup></material-confirm-popup>
  </c-dialog>
</template>

<script setup name="">
import { h, ref, computed, onMounted } from 'vue';

import Sortable from 'sortablejs';

import MaterialPreview from '@/components/material-preview/index.vue';
import SelectImagePopup from '@/components/select-image-popup/index.vue';
import SelectTextPopup from '@/components/select-text-popup/index.vue';
import MaterialPreviewPopup from '@/components/material-preview-popup/index.vue';
import MaterialConfirmPopup from '@/components/material-confirm-popup/index.vue';

// hooks
import { useFetch } from '@/hooks/useFetch/index.js';

import { getTempList, previewMateralV2, createMateralV2 } from '@/apis/material';

import { MiniEnt, TempNumber } from '@/config/global-variable';

import { MessageBox } from '@/utils/message-box';

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

// user
import { useUserStore } from '@/pinia/modules/user.js';
const userStore = useUserStore();

import { useGlobalStore } from '@/pinia/modules/global';
const globalStore = useGlobalStore();

// router
import { useRouter } from 'vue-router';
const router = useRouter();

import { v4 } from 'uuid';

const emit = defineEmits(['refresh']);

const props = defineProps({
  // 0 普通用户 1 admin
  userType: {
    type: [String, Number],
    default: 0,
  },
});

const materialRef = ref();

const tableData = ref([
  { id: v4(), image_type: '', image_list: [], text_list: [], image_temp_id: '', text_temp_id: '' },
]);

const tableIndex = ref('');

const searchParams = ref({
  temp_number_id: '',
  mini_ent_type: 0,
});

const getTempMap = computed(() => {
  return (tempData.value.data || []).reduce((result, item) => {
    result[item.value] = item;
    return result;
  }, {});
});

const isCan = computed(() => {
  for (const item of tableData.value) {
    console.log(item, 'item---------');

    if (!item.image_type) {
      return false;
    }

    if (!item.image_list.length && !item.text_list.length) {
      return false;
    }

    if (item.image_list.length) {
      if (!item.image_temp_id) {
        return false;
      }
    }

    if (item.text_list.length) {
      if (!item.text_temp_id) {
        return false;
      }
    }
  }
  return true;
});

const getRowCount = computed(() => {
  const { image_type } = tableData.value[tableIndex.value];
  if (image_type == 5) {
    return globalStore.device.type == 'desktop' ? 3 : 2;
  } else {
    return globalStore.device.type == 'desktop' ? 5 : 4;
  }
});

const getItemSize = computed(() => {
  const { image_type } = tableData.value[tableIndex.value];
  if (image_type == 5) {
    return 150;
  } else {
    return 90;
  }
});

const getImageType = computed(() => {
  const { image_type } = tableData.value[tableIndex.value];

  return image_type;
});

const { loading: tempLoading, data: tempData } = useFetch({
  api: getTempList,
});

const handleImageModal = (row, index) => {
  tableIndex.value = index;
  modalStore.openModal('select-image-popup', row);
};

const handleTextModal = (row, index) => {
  tableIndex.value = index;
  modalStore.openModal('select-text-popup', row);
};

const onSelectImageEnd = (list) => {
  console.log(list, 'list');
  tableData.value[tableIndex.value].image_list = list;

  onRefreshMateral();
};

const onSelectTextEnd = (list) => {
  console.log(list, 'list');

  tableData.value[tableIndex.value].text_list = list;

  onRefreshMateral();
};

const handleAddMateral = () => {
  tableData.value.push({
    id: v4(),
    image_type: '',
    image_list: [],
    text_list: [],
    image_temp_id: '',
    text_temp_id: '',
  });
};

const handleDelete = (row, index) => {
  tableData.value.splice(index, 1);
};

const handleCancel = () => {
  router.back();
};

const previewLoading = ref(false);
const tableLoading = ref(false);
const initGenerateMateral = async () => {
  if (globalStore.device.type == 'desktop') {
    previewLoading.value = true;
  } else {
    tableLoading.value = true;
  }
  const res = await previewMateralV2({
    list: tableData.value,
    ...searchParams.value,
  });
  if (globalStore.device.type == 'desktop') {
    previewLoading.value = false;
  } else {
    tableLoading.value = false;
  }
  if (res.code == 0) {
    if (globalStore.device.type == 'desktop') {
      materialRef.value && materialRef.value.innerHTML(res.data);
    } else {
      modalStore.openModal('material-preview-popup', { HTML: res.data });
    }
  }
};

const onImageTypeChange = (row) => {
  row.image_temp_id = '';
  materialRef.value && materialRef.value.innerHTML('');
  row.image_list = [];
  onRefreshMateral();
};

const onRefreshMateral = () => {
  console.log(isCan.value, 'isCan.value');

  if (!isCan.value) {
    return;
  }

  if (globalStore.device.type == 'desktop') {
    initGenerateMateral();
  }
};

const handleConfirm = async () => {
  let content = [];
  for (const item of tableData.value) {
    content.push({
      image_type: item.image_type,

      image_ids: item.image_list.map((v) => v._id),
      image_temp_id: item.image_temp_id,

      text_ids: item.text_list.map((v) => v._id),
      text_temp_id: item.text_temp_id,
    });
  }

  let obj = {
    content: content,
    ...searchParams.value,
  };

  if (props.userType == 1) {
    obj['userid'] = -1;
  } else {
    obj['mini_userid'] = userStore?.userInfo?.miniData?._id;
  }

  modalStore.openModal('material-confirm-popup', obj);
};

// 行拖拽
const rowDrop = () => {
  const tbody = document.querySelector('.table-template__table tbody');
  Sortable.create(tbody, {
    group: {
      name: 'shared',
      pull: true,
      put: true,
    },
    handle: '.table-drag-img',
    animation: 150,
    onEnd({ newIndex, oldIndex }) {
      console.log(newIndex, oldIndex, 'newIndex, oldIndex');

      const currRow = tableData.value.splice(oldIndex, 1)[0];

      tableData.value.splice(newIndex, 0, currRow);

      onRefreshMateral();
    },
  });
};

onMounted(() => {
  rowDrop();
});
</script>

<style lang="scss" scoped>
.materal {
  height: 100%;
  display: flex;
  overflow-x: auto;
}

.materal-left {
  min-width: 460px;
  width: 100%;
  overflow: auto;
  padding: 20px;
  box-sizing: border-box;
  @include card-box;
  display: flex;
  flex-direction: column;
}

.image-list {
  width: 100%;
  margin-top: 10px;
  margin-bottom: 0 !important;
}

.image-list-item {
  width: 42px;
  aspect-ratio: 1/1;
  // background-color: #eee;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  object-fit: contain;
}

.materal-right {
  width: 375px;
  flex-shrink: 0;
  overflow: hidden;
  margin-left: 12px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  @include card-box;
}

.materal-right-title {
  padding-top: 12px;
  box-sizing: border-box;
  margin-left: 12px;
}

.materal-right-preview {
  height: 100%;
  overflow: hidden;
}

.materal-table-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  // position: sticky;
  // bottom: 0;
  margin-top: 10px;
}

.select-box {
  height: 100px;
  width: 100%;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.text-item {
  white-space: pre-wrap;
  line-height: 1.6;
  font-size: 12px;
  box-sizing: border-box;
  border-bottom: 1px dashed #eee;
  padding: 8px 12px;
  box-sizing: border-box;
}

.materal-footer {
  width: 100%;
  display: flex;
  justify-content: center;
  position: sticky;
  bottom: 0;
}

.mini-ent-select {
  display: flex;
  flex-direction: column;

  & > span {
    line-height: 1.8;
  }

  & > span:nth-child(2) {
    font-size: 12px;
    color: #999;
  }
}

.scroller-image {
  width: 92px;
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;
  border: 1px solid #e6e6e6;
  margin: 0 4px 4px 0;
}

.scroller-image-item {
  width: 30px;
  height: auto;
  aspect-ratio: 1/1;
  box-sizing: border-box;
}
</style>
